package com.hck.weight_test.ObtainWeighing.device;

import com.hck.weight_test.ObtainWeighing.bean.DeviceBean;
import com.hck.weight_test.ObtainWeighing.interfaces.IDeviceGetDataListener;
import android_serialport_api.SerialPortDevice;

public class DeviceManger {
    private DeviceManger(){}
    private static DeviceManger deviceManger;

    public static DeviceManger getDeviceManger(){
        if (deviceManger==null){
            deviceManger=new DeviceManger();
        }
        return deviceManger;
    }
     private SerialPortDevice mCurrentDevice;
     private DeviceReader mDeviceReader;

    public boolean startGetWeight(DeviceBean device,IDeviceGetDataListener listener) {
        if (this.mCurrentDevice != null) {
            close();
            this.mCurrentDevice = null;
        }
        if (!open(device,listener)) {
            return false;
        }
        return true;
    }

    // 打开设备，不会重复打开
    private boolean open(final DeviceBean device,IDeviceGetDataListener listener) {
        synchronized (this) {
            if (mCurrentDevice == null) {
                SerialPortDevice serialPortDevice = new SerialPortDevice(device.getDeviceId(), device.getBaudrate(), device.getFlags());
                if (!serialPortDevice.open()) {
                    return false;
                }
               mCurrentDevice=serialPortDevice;
            }
            if (mDeviceReader!=null){
                mDeviceReader.cancel();
                mDeviceReader=null;
            }
            // 开启读取数据线程
            mDeviceReader = new DeviceReader(device, mCurrentDevice, listener);
            mDeviceReader.start();
            return true;
        }
    }

    public void close() {
            if (mCurrentDevice != null) {
                mCurrentDevice.close();
                mCurrentDevice=null;
            }
            if (mDeviceReader != null) {
                mDeviceReader.cancel();
                mDeviceReader=null;
            }

    }

}
